package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.SubstationDAO;
import ee.maoinvest.backend.model.data.Substation;

public class SubstationDAOPostgresqlImpl implements SubstationDAO, Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 172698116969678399L;
	
	Logger logger = Logger.getLogger(SubstationDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public SubstationDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
//-----------------START OF BASIC CRUD-----------------------------------

	@Override
	public int insertSubstation(Substation substation) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Substations (substationName, dateInserted, dateUpdated, isInUse, isWrittenOff, dateOfWriteOff) " + 
				"VALUES (?, ?, ?, ?, ?, ?);";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setString	(	1, substation.getSubstationName());
			preparedStatement.setDate	(	2, substation.getDateInserted());
			preparedStatement.setObject	(	3, substation.getDateUpdated(), Types.DATE);
			preparedStatement.setBoolean(	4, substation.getIsInUse());
			preparedStatement.setBoolean(	5, substation.getIsWrittenOff());
			preparedStatement.setObject	(	6, substation.getDateOfWriteOff(), Types.DATE);
			
			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				substation.setSubstationID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public Substation getSubstationByID(int substationID) 
	{
		resultSet = null;
		Substation substationRetrieved = null;
		sql = "SELECT * FROM Substations WHERE substationID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, substationID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				substationRetrieved = new Substation();
				substationRetrieved.setSubstationID(resultSet.getInt("substationID"));
				substationRetrieved.setSubstationName(resultSet.getString("substationName"));
				substationRetrieved.setDateInserted(resultSet.getDate("dateInserted"));
				substationRetrieved.setDateUpdated((Date) resultSet.getObject("dateUpdated"));
				substationRetrieved.setIsInUse(resultSet.getBoolean("isInUse"));
				substationRetrieved.setIsWrittenOff(resultSet.getBoolean("isWrittenOff"));
				substationRetrieved.setDateOfWriteOff((Date) resultSet.getObject("dateOfWriteOff"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return substationRetrieved;
	}

	@Override
	public int updateSubstation(Substation substation) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Substations " + 
				"SET substationName = ?, dateInserted = ?, dateUpdated = ?, isInUse = ?, isWrittenOff = ?, dateOfWriteOff = ? " + 
				"WHERE substationID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setString	(	1, substation.getSubstationName());
			preparedStatement.setDate	(	2, substation.getDateInserted());
			preparedStatement.setObject	(	3, substation.getDateUpdated(), Types.DATE);
			preparedStatement.setBoolean(	4, substation.getIsInUse());
			preparedStatement.setBoolean(	5, substation.getIsWrittenOff());
			preparedStatement.setObject	(	6, substation.getDateOfWriteOff(), Types.DATE);
			preparedStatement.setInt	(	7, substation.getSubstationID());
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public int deleteSubstation(int substationID) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "DELETE FROM Substations WHERE substationID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			preparedStatement.setInt(1, substationID);
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Deletion successful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.info("Deletion unsuccessful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch(SQLException e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
//-----------------END OF BASIC CRUD-----------------------------------	

	@Override
	public List<Substation> getAllSubstations() 
	{
		List<Substation> listOfSubstations = new ArrayList<Substation>();
		Substation substationRetrieved = null;
		sql = "SELECT * FROM Substations ORDER BY substationName;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				substationRetrieved = fillSubstationObjectWithDataRetrievedFromDB();
				
				listOfSubstations.add(substationRetrieved);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfSubstations;
	}

	@Override
	public List<Substation> getAllSubstationsThatAreNotWrittenOff() 
	{
		List<Substation> listOfSubstations = new ArrayList<Substation>();
		Substation substationRetrieved = null;
		sql = "SELECT * FROM Substations WHERE isWrittenOff = false ORDER BY substationName;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				substationRetrieved = fillSubstationObjectWithDataRetrievedFromDB();
				listOfSubstations.add(substationRetrieved);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfSubstations;
	}

	@Override
	public int setIsSubstationInUse(int substationID, boolean isInUse) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Substations " + 
				"SET isInUse = ? " +
				"WHERE substationID = ?;"; 
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setBoolean(1, isInUse);
			preparedStatement.setInt	(2, substationID);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
	
	//Helper methods
	private Substation fillSubstationObjectWithDataRetrievedFromDB()
	{
		Substation substationRetrieved = null;
		try
		{
			substationRetrieved = new Substation();
			substationRetrieved.setSubstationID(resultSet.getInt("substationID"));
			substationRetrieved.setSubstationName(resultSet.getString("substationName"));
			substationRetrieved.setDateInserted(resultSet.getDate("dateInserted"));
			substationRetrieved.setDateUpdated((Date) resultSet.getObject("dateUpdated"));
			substationRetrieved.setIsInUse(resultSet.getBoolean("isInUse"));
			substationRetrieved.setIsWrittenOff(resultSet.getBoolean("isWrittenOff"));
			substationRetrieved.setDateOfWriteOff((Date) resultSet.getObject("dateOfWriteOff"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return substationRetrieved;
	}
}
